package com.abase.site.server;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.util.encoders.Base64;

import com.abase.site.shared.AbaseProfile;
import com.abase.site.shared.constants.AbaseConstants;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.SerializationPolicy;
import com.google.gwt.user.server.rpc.impl.SerializabilityUtil;


public class CookieHelper implements IsSerializable {
	
	//private static final Log logger = LogFactory.getLog(CookieHelper.class);
	
	 /**
	   * Return the AbaseCookie instance of the caller.
	   *
	   * @param request Request to extract the cookie from.
	   * @return a AbaseCookie instance or null if no cookie could be extracted
	   */
	  public static AbaseProfile getCookie(final HttpServletRequest request) {

	    if (request.getCookies() != null) {
	      for (final Cookie cookie: request.getCookies()) {
	        if (AbaseConstants.ABASEAUTH.equals(cookie.getName())) {

	          AbaseProfile abaseCookie = new AbaseProfile();

	          try {
	        	  abaseCookie = (AbaseProfile) SerializabilityUtil.decodeSerializedInstanceReference(new String(Base64.decode(cookie.getValue().getBytes())));
	          } catch (final Exception ex) {
	            abaseCookie = null;
	          }

	          return abaseCookie;
	        }
	      }
	    }

	    return null;
	  }
	  
	  /**
	   * Return an encrypted String value for the cookie or null if an error occurred.
	   *
	   * @param profil
	   * @return
	   */
	  public static String getCookieValue(final AbaseProfile profil) {
		  
		  SerializationPolicy policy = new SerializationPolicy() {
			
			@Override
			public void validateSerialize(Class<?> clazz) throws SerializationException {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void validateDeserialize(Class<?> clazz)
					throws SerializationException {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean shouldSerializeFields(Class<?> clazz) {
				if (clazz.equals(profil.getClass())) {
					return true;
				}
				return false;
			}
			
			@Override
			public boolean shouldDeserializeFields(Class<?> clazz) {
				if (clazz.equals(profil.getClass())) {
					return true;
				}
				return false;
			}
		};
	    try {
	      return new String(Base64.encode( SerializabilityUtil.encodeSerializedInstanceReference(profil.getClass(), policy).getBytes()));
	    } catch (final Exception ex) {
	      //logger.error("getCookieValue", ex);
	    }
	    return null;
	  }
}
